<?php 

class Model_Film {
    
    public function saveFilm($title,
                             $link,
                             $rating,
                             $image,
                             $description,
                             $categories
                            ){
        $filmTbl = new Model_DbTable_Films();
        $row = $filmTbl->fetchRow("`link` = '$link'");
        if ($row) { // updating record
            $row->title = $title;
            $row->rating = $rating;
            $row->image_ext_url = $image;
         /**   if($image){
                $cUrl = new Lib2k_Parsing_cUrl();
                $imgPath = $cUrl->save_image($image, APPLICATION_PATH . "/../temp");
                $imageModel = new Model_Image($imgPath);
                $imageUrlPath = $imageModel->saveOrig();//exit($imageUrlPath);
                $row->image = $imageUrlPath;
            }  */                      
            $row->description = $description;
            $fId = $row->save();
            $filmCategoryModel = new Model_FilmCategory();
            $filmCategoryModel->removeAllCatsFromFilm($fId);// removing old cats
            if(is_array($categories)) {
                $catModel = new Model_Category();
                foreach($categories as $cat) {
                    $row = $catModel->getByLink($cat['link']);
                    if($row) {
                        $catId = $row->id;
                    } else {
                        $catId = $catModel->add($cat['title'], $cat['link']);
                    }
                    $filmCategoryModel->add($fId, $catId);                                        
                }
            }
            
        } else { // adding new record
            $row = $filmTbl->createRow();
            $row->title = $title;
            $row->link = $link;
            $row->rating = $rating;
            $row->image_ext_url = $image;
            // saving image url for future parsing
        /**    if($image){          
                $cUrl = new Lib2k_Parsing_cUrl();
                $imgPath = $cUrl->save_image($image, APPLICATION_PATH . "/../temp");
                $imageModel = new Model_Image($imgPath);
                $imageUrlPath = $imageModel->saveOrig();
                $imageModel->removeTempFile();// delete temp file
                $row->image = $imageUrlPath;
               // exit( $imgPath . "<br/>" . $imageUrlPath);
            } */ 
            $row->description = $description;
            $fId = $row->save();    
            $filmCategoryModel = new Model_FilmCategory();
            if(is_array($categories)) {
                $catModel = new Model_Category();
                foreach($categories as $cat) {
                    $row = $catModel->getByLink($cat['link']);
                    if($row) {
                        $catId = $row->id;
                    } else {
                        $catId = $catModel->add($cat['title'], $cat['link']);
                    }
                    $filmCategoryModel->add($fId, $catId);                    
                }
            }                    
        }
        
    }
    
    public function getCategories($filmId) {
        $filmCatsTBL = new Model_DbTable_FilmCategories();
        $query = "SELECT * FROM `categories` WHERE `id` in ( SELECT `categoryId` from `filmCategories` WHERE `filmId` = '$filmId' )";
        $rows = $filmCatsTBL->getAdapter()->query($query)->fetchAll(Zend_Db::FETCH_ASSOC);
        return $rows; 
    }
    
    public function getAllCategories() {
        $filmCatsTBL = new Model_DbTable_Categories();
        $rows = $filmCatsTBL->fetchAll(null, 'title')->toArray();
        return $rows; 
    }    
    
    public function search($searchText = null, $categories = null, $limit = 10, $offset = 0){
        $filmsTbl = new Model_DbTable_Films();
        $query = "SELECT *," 
               . "REPLACE(UPPER(title), UPPER('$searchText'), UPPER('<span class=\"searchshow\">$searchText</span>')) as title ,"
               . "REPLACE(UPPER(description), UPPER('$searchText'), UPPER('<span class=\"searchshow\">$searchText</span>')) as description " 
               . ' FROM `films` ';
        if($searchText || $categories) {
            $query = $query . " WHERE ";
            
            if($searchText) {
                $query = $query . "(`title` like '%$searchText%' OR `description` like '%$searchText%')";
            }     
            
            if($categories) {
                if ($searchText) {
                    $query = $query . " AND ";
                }
               // $catsIds = implode(',', $categories);
                $subQuery = "";
                if(is_array($categories)) {                                    
                    foreach($categories as $cItem) {
                        $subQuery = $subQuery . " AND `filmId` in ( SELECT `filmId` FROM `filmCategories` WHERE `categoryId` = '$cItem')";
                    }
                } else {
                    $subQuery = $subQuery . " AND `categoryId` = '$categories'";
                }
                $subQuery = substr($subQuery,4, strlen($subQuery) - 3);
                $query = $query . "`id` IN (SELECT `filmId` FROM `filmCategories` WHERE $subQuery )";
            }              
                               
        }
        

        $query = $query . "ORDER BY `rating` DESC LIMIT $offset,$limit ";
       // Zend_Debug::dump($query);
        //$films = $filmsTbl->fetchAll($query, null, 10, 0);
        $films = $filmsTbl->getAdapter()->query($query)->fetchAll(Zend_Db::FETCH_ASSOC);
        return $films;
    }
    
    public function searchCount($searchText = null, $categories = null){
        $filmsTbl = new Model_DbTable_Films();
        $query = 'SELECT count(*) as count FROM `films`';
        if($searchText || $categories) {
            $query = $query . " WHERE ";
            
            if($searchText) {
                $query = $query . "(`title` like '%$searchText%' OR `description` like '%$searchText%')";
            }     
            
            if($categories) {
                if ($searchText) {
                    $query = $query . " AND ";
                }
               // $catsIds = implode(',', $categories);
                $subQuery = "";
                if(is_array($categories)) {                                    
                    foreach($categories as $cItem) {
                        $subQuery = $subQuery . " AND `filmId` in ( SELECT `filmId` FROM `filmCategories` WHERE `categoryId` = '$cItem')";
                    }
                } else {
                    $subQuery = $subQuery . " AND `categoryId` = '$categories'";
                }
                $subQuery = substr($subQuery,4, strlen($subQuery) - 3);
                $query = $query . "`id` IN (SELECT `filmId` FROM `filmCategories` WHERE $subQuery )";
            }              
                               
        }
        

       // $query = $query . " LIMIT $offset,$limit ";
      //  Zend_Debug::dump($query);
        //$films = $filmsTbl->fetchAll($query, null, 10, 0);
        $films = $filmsTbl->getAdapter()->query($query)->fetchAll(Zend_Db::FETCH_ASSOC);
        return $films;
    }   
    
    public function parseFilmImages($count){
        $filmTbl = new Model_DbTable_Films();
        $films = $filmTbl->fetchAll("`image` IS null AND `image_ext_url` IS NOT null", 'rating DESC', $count);
        $count = 0;
        foreach($films as $item) {
            set_time_limit(30);
            $film = $filmTbl->fetchRow("`id` = '$item->id'");
            if($film){                          
               if($film->image_ext_url){          
                    $cUrl = new Lib2k_Parsing_cUrl();
                    $imgPath = $cUrl->save_image($film->image_ext_url, APPLICATION_PATH . "/../temp");
                    $imageModel = new Model_Image($imgPath);
                    $imageUrlPath = $imageModel->saveOrig();
                    $imageModel->removeTempFile();// delete temp file
                    $film->image = $imageUrlPath;  
                    $film->save();
                    $count++;
                    Zend_Debug::dump($count);             
               }
           }            
        }       
    } 
    
    
    
}